import os
import re
import sys
import time
import traceback

import openpyxl
from openpyxl.styles import Font, PatternFill, Border, Side, Alignment
from openpyxl.worksheet.datavalidation import DataValidation

from framework.android.androiddevice import ADB
from Utils.TestCase import TestCase
from Utils.zentao.zentaoTools import zentaoTools
from framework.utils.log_record_util import get_logger
logger = get_logger()
def getCurrentTimeUnderline():
    return time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime(time.time()))

class api_tools():
    testcase_filename = r"D:\\log_aip\\testcase.xlsx"

    path = r"G:\git\YZSmartPosApiTest\yztester\src\main\java\com\yz\smartpos\yztester\apifuntest\tests\\"

    product = "Z6"

    zentao = None

    runid_refresh_flag = 0

    def __init__(self, zentao_tool):
        self.zentao_tool = zentao_tool

    @staticmethod
    def test_pull_log():
        # SHVJQA0114 SHVJQA00VU
        devicename = "SHVJQA00VU"
        log_path = "D:\\log_aip\\YLog\\"

        devices = ADB.list_device()
        if len(devices) != 0:
            devicename = devices[0]
            os.system("adb -s %s pull /sdcard/Android/data/com.yz.smartpos.yztester/files/Results %s" % (
                devicename, log_path))
        else:
            logger.info("\n\n!!!!!! NO DEVICES!!!!!!!!!!!!")
            devicename = "unkow"
            return

        time_str = getCurrentTimeUnderline()
        os.system("adb -s %s pull /sdcard/ylog D:\\log_aip\\YLog\\ylog_%s" % (devicename, time_str))
        os.system("adb -s %s shell rm /sdcard/ylog -rf" % devicename)
        logger.info("file://192.168.11.38/YLog/ylog_" + time_str)

    @staticmethod
    def write_excel(bug_file, sheet_name, testcase_list):
        if not os.path.exists(bug_file):
            workbook = openpyxl.Workbook()
        else:
            workbook = openpyxl.load_workbook(bug_file)

        logger.info("\nwrite_excel1:")
        logger.info(sheet_name)
        logger.info(workbook.sheetnames)
        logger.info("\n")

        if sheet_name in workbook.sheetnames:
            sheet = workbook[sheet_name]
            workbook.remove(sheet)

        workbook.create_sheet(sheet_name, 0)
        workbook.save(sheet_name)

        sheet = workbook[sheet_name]
        sheet.append(
            ["", "用例名", "测试目的", "前提", "测试步骤", "期望结果", "测试方式", "实际结果", "备注"])

        for testcase in testcase_list:
            sheet.append(["", testcase.TCName, testcase.TCSummary, testcase.TCPrecondition,
                          testcase.TCAction.replace("\\n", '\n').replace("\\r\\n", '\n'),
                          testcase.TCResult.replace("\\n", '\n').replace("\\r\\n", '\n'), testcase.TCMode])

        side = Side(border_style='thin', color='000000')
        align = Alignment(horizontal='center', )
        for row in sheet['A1:I1']:
            for cell in row:
                cell.font = Font(name=u'微软雅黑', size=11, bold=True, color='000000')
                cell.alignment = align
                cell.fill = PatternFill(fill_type='solid', start_color='5B9BD5')
                cell.border = Border(left=side, right=side, bottom=side, top=side)
                cell

        sheet.column_dimensions['B'].width = 20
        sheet.column_dimensions['C'].width = 30
        sheet.column_dimensions['D'].width = 10
        sheet.column_dimensions['E'].width = 50
        sheet.column_dimensions['F'].width = 40

        max_column = sheet.max_column
        max_row = sheet.max_row
        logger.info("max_row")
        logger.info(max_row)

        for column in range(2, max_column + 1):
            for row in range(2, max_row + 1):
                sheet.cell(row=row, column=column).font = Font(name=u'微软雅黑', size=10, color='000000')

        sheet.freeze_panes = "A1"  # 冻结首行
        dv = DataValidation(type="list", formula1='"PASS,FAIL,BLOCK"', allow_blank=True)  # 下拉框可选择值为：a、b、c
        dv.add("H2:H" + str((row + 1)))  # 这里样例是给P列添加下拉框，从2行到6行
        sheet.add_data_validation(dv)  # 给sheet添加下拉框
        workbook.save(bug_file)

    @staticmethod
    def parser_testcase(path, Moudle):
        testcase_list = []
        # parser 测试代码java文件，获取testcase并写入excel中
        file = None
        Name_parttern = None

        file = path + Moudle + ".java"
        Name_parttern = re.compile(r'^    public void (.*\d)\(\) *\{', flags=re.M)

        Summary_parttern = re.compile(r'^    @TCSummary\(\"(.*)\"\)', flags=re.M)
        Precondition_parttern = re.compile(r'^    @TCPrecondition\(\"(.*?)\"\)', flags=re.M | re.DOTALL)
        Action_parttern = re.compile(r'^    @TCAction\(\"(.*?)\"\)', flags=re.M | re.DOTALL)
        Result_parttern = re.compile(r'^    @TCResult\(\"(.*?)\"\)', flags=re.M | re.DOTALL)
        Mode_parttern = re.compile(r'^    @TCMode\(\"(.*)\"\)', flags=re.M)

        with open(file, "r", encoding='utf-8') as f:
            context = f.read()
            tmpcase_list = context.split('@Test')

        for context in tmpcase_list[1:]:
            TCSummary = ""
            TCName = ""
            try:
                TCName = re.findall(Name_parttern, context)[0]
            except Exception as e:
                continue

            try:
                TCSummary = re.findall(Summary_parttern, context)[0]
                TCPrecondition = re.findall(Precondition_parttern, context)[0].replace("\" +", "").replace("            \"", "")
                TCAction = re.findall(Action_parttern, context)[0].replace("\" +", "").replace("            \"", "")
                TCResult = re.findall(Result_parttern, context)[0].replace("\" +", "").replace("            \"", "")
                TCMode = re.findall(Mode_parttern, context)[0]
            except Exception as e:
                # logger.info(Moudle)
                # logger.info(e)
                # logger.info(context[:200])
                continue
            if TCName == "" or TCSummary == "":
                continue
            testcase_list.append(TestCase(TCName=TCName, TCSummary=TCSummary, TCPrecondition=TCPrecondition,
                                          TCAction=TCAction, TCResult=TCResult, TCMode=TCMode))
        return testcase_list
        pass

    @staticmethod
    def parser_testcase_c(path, Moudle):
        testcase_list = []
        # parser 测试代码java文件，获取testcase并写入excel中
        file = None
        Name_parttern = None

        file = path + Moudle + ".c"
        Name_parttern = re.compile(r'^uint8_t {1,2}(.*\d+)\(.*\)', flags=re.M)

        Summary_parttern = re.compile(r'^    @TCSummary\(\"(.*)\"\)', flags=re.M)
        Precondition_parttern = re.compile(r'^    @TCPrecondition\(\"(.*?)\"\)', flags=re.M | re.DOTALL)
        Action_parttern = re.compile(r'^    @TCAction\(\"(.*?)\"\)', flags=re.M | re.DOTALL)
        Result_parttern = re.compile(r'^    @TCResult\(\"(.*?)\"\)', flags=re.M | re.DOTALL)
        Mode_parttern = re.compile(r'^    @TCMode\(\"(.*)\"\)', flags=re.M)

        with open(file, "r", encoding='utf-8') as f:
            context = f.read()
            tmpcase_list = context.split('@Test')

        for context in tmpcase_list[1:]:
            TCSummary = ""
            TCName = ""
            try:
                TCName = re.findall(Name_parttern, context)[0]
            except Exception as e:
                continue

            try:
                TCSummary = re.findall(Summary_parttern, context)[0]
                TCPrecondition = re.findall(Precondition_parttern, context)[0].replace("\" +", "").replace(
                    "            \"", "")
                TCAction = re.findall(Action_parttern, context)[0].replace("\" +", "").replace("            \"", "")
                TCResult = re.findall(Result_parttern, context)[0].replace("\" +", "").replace("            \"", "")
                TCMode = re.findall(Mode_parttern, context)[0]
            except Exception as e:
                # logger.info(Moudle)
                # logger.info(e)
                # logger.info(context[:200])
                continue
            if TCName == "" or TCSummary == "":
                continue
            testcase_list.append(TestCase(TCName=TCName, TCSummary=TCSummary, TCPrecondition=TCPrecondition,
                                          TCAction=TCAction, TCResult=TCResult, TCMode=TCMode))
        return testcase_list
        pass

    @staticmethod
    def test_write_testcase_toExcel():
        Module = "PinPadDevice"
        global path
        testcase_list = api_tools.parser_testcase(path, Module)
        api_tools.write_excel(api_tools.testcase_filename, Module, testcase_list)

    @staticmethod
    def test_write_testcase_toExcel_all():
        Moudles = ["PosTerminal", "CardReaderDevice", "EMVDevice", "PinPadDevice", "PrinterDevice", "ScannerDevice", "PMDevice", "WifiTest",
                   "TagDevice"]
        global path

        for Moudle in Moudles:
            testcase_list = api_tools.parser_testcase(path, Moudle)
            api_tools.write_excel(api_tools.testcase_filename, Moudle, testcase_list)
    '''
    {
        '20': 'Z7',
        '19': 'Z6',
        '18': 'N1',
        '17': 'Q50A',
        '16': 'YZ07',
        '15': 'Q50',
        '13': 'YS200',
        '12': 'YZ30',
        '11': 'YZ21',
        '9': '物料导入',
        '8': 'YZ06',
        '7': 'Tools',
        '6': 'System',
        '5': 'CS21L',
        '4': 'YZ05',
        '3': 'CS11',
        '2': 'YZ61',
        '1': 'CS21'
    }
    '''
    def upload_testcase_toZentao(self, Module_tmp, isC, isLib=False, path_tmp=path, Logger=None):
        testcase_list = []

        if isC == False:
            testcase_list = api_tools.parser_testcase(path_tmp, Module_tmp)
        else:
            testcase_list = api_tools.parser_testcase_c(path_tmp, Module_tmp)

        testcase_tmp = testcase_list
        # logger.info(testcase_list)
        Module = Module_tmp

        if isLib:
            testcase_list_zentao = self.zentao_tool.caselib_browse(Module)
        else:
            testcase_list_zentao = self.zentao_tool.testcase_browse(Module)
            pass
        for testcase in testcase_list:
            # logger.info(testcase)
            if testcase.TCName in testcase_list_zentao:
                if testcase.compareTo(testcase_list_zentao[testcase.TCName]) == True:
                    continue
                else:
                    # 修改 case
                    logger.info("modify case:" + testcase.TCName)
                    if Logger is not None:
                        Logger.append("modify case:" + testcase.TCName)
                    # testcase.compareTo(testcase_list_zentao[testcase.TCName])
                    self.zentao_tool.testcase_edit(testcase_list_zentao[testcase.TCName].id, testcase, isLib)

                    continue
            logger.info("creat case:" + testcase.TCName)
            if Logger is not None:
                Logger.append("creat case:" + testcase.TCName)

            if isLib:
                self.zentao_tool.caselib_createCase(testcase, Module)
            else:
                self.zentao_tool.testcase_create(testcase, Module)
                pass
            time.sleep(0.1)
            # break

    def test_zz(self):
        Moudle = "PinPadDevice"
        # testcase = self.zentao_tool.testcase_view('5953-1-testtask-2470')
        # self.zentao_tool.testcase_delete(range(4844, 5836))
        # testcase_list_zentao = self.zentao_tool.caselib_browse(Moudle)
        testcase_list_zentao = self.zentao_tool.testcase_browse_all()
        # self.zentao_tool.testtask_cases('2470')
        self.zentao_tool.testtask_runCase('19084', '57816', 'fail', "1234", "5836")  # upgradeAndroidOS_tol1

    @staticmethod
    def test_java_fun(path, Moudle, Modules, Logger=None):
        # parser 测试代码java文件，解析testcaseList
        fun_parttern = re.compile(r'^    public void (.*)\(\) *\{', flags=re.M)
        type_parttern = re.compile(r'^    @TCMode\(\"(.*)\"\)', flags=re.M)
        logger.info("Moudle:" + Moudle)

        file = path + Moudle + ".java"
        logger.info("file:" + file)

        with open(file, "r", encoding='utf-8') as f:
            context = f.read()
            funs_tmp = re.findall(fun_parttern, context)
            types = re.findall(type_parttern, context)
            # t = ret.groups()
            funs = []
            for fun in funs_tmp:
                if fun != "run":
                    funs.append(fun)
            logger.info("func:" + str(len(funs)) + " types:" + str(len(types)) + "\n")
            logger.info(funs)
            logger.info(types)

            if Logger != None:
                Logger.append("new TestCase(\"RunAllAuto\"),")
                Logger.append("new TestCase(\"RunAllAutoFail\"),")
                Logger.append("new TestCase(\"RunAllAutoNotRun\"),")
            else:
                logger.info("new TestCase(\"RunAllAuto\"),")
                logger.info("new TestCase(\"RunAllAutoFail\"),")
                logger.info("new TestCase(\"RunAllAutoNotRun\"),")
                if Moudle == "PrinterDevice":
                    logger.info("new TestCase(\"RunAllAutoNotRun_paper\"),")
                elif Moudle == "CardReaderDevice":
                    logger.info("new TestCase(\"RunAllAutoNotRun_rf\"),")
                    logger.info("new TestCase(\"RunAllAutoNotRun_ic\"),")
                elif Moudle == "ScannerDevice":
                    logger.info("new TestCase(\"RunAllAutoNotRun_scan\"),")

            index1 = Modules.index(Moudle)
            for i in range(0, len(types)):
                if Logger != None:
                    Logger.append(
                        "new TestCase(" + str(index1) + ", " + str(i + 3) + ", Module, \"" + funs[i] + "\", TestCase." +
                        types[
                            i] + "),")
                logger.info(
                    "new TestCase(" + str(index1) + ", " + str(i + 3) + ", Module, \"" + funs[i] + "\", TestCase." + types[
                        i] + "),")
        pass

    @staticmethod
    def test_rtos_fun(path, Moudle, Modules, Logger=None):
        # parser 测试代码C文件，解析testcaseList
        fun_parttern = re.compile(r'^uint8_t {1,2}(.*\d+)\(.*\)', flags=re.M)
        type_parttern = re.compile(r'^    @TCMode\(\"(.*)\"\)', flags=re.M)
        prefix_parttern = re.compile(r'(.*)_.*\d+', flags=re.M)

        logger.info("Moudle:" + Moudle)

        file = path + Moudle + ".c"
        logger.info("file:" + file)

        with open(file, "r", encoding='utf-8') as f:
            context = f.read()
            funs_tmp = re.findall(fun_parttern, context)
            types = re.findall(type_parttern, context)
            logger.info(funs_tmp)
            logger.info(types)
            # t = ret.groups()
            funs = []
            for fun in funs_tmp:
                if fun != "run":
                    funs.append(fun)
            logger.info(funs)
            logger.info(types)

            index1 = Modules.index(Moudle)
            prefix = "noexit"
            prefix_list = []
            if Logger != None:
                if len(funs) != len(types):
                    logger.info("ERR!! func:" + str(len(funs)) + " types:" + str(len(types)) + "\n")
                    if Logger != None:
                        Logger.append("ERR!! func:" + str(len(funs)) + " types:" + str(len(types)));
                for i in range(0, len(types)):
                    Logger.append("    {" + "\"" + funs[i] + "\", " + funs[i] + ", " + "STATUS_NOTRUN" + ", " + types[i] + ", 1" + "},")


    @staticmethod
    def test_result_adb_pull():
        # 上传测试结果到禅道
        # 需提供2个参数：  1.local_path(本地路径，存放临时日志)；2.testtask_id(禅道上的测试单ID)

        global local_path

        # log_path = os.path.join(local_path, testtask_id)
        log_path = os.path.join(local_path, "Results")
        case_runned = os.path.join(log_path, "case_runned.txt")

        testLog_file = os.path.join(log_path, "test.log")
        testLog_pm_file = os.path.join(log_path, "test_pm.log")

        case_runned_dict = {}
        case_upload_ok_list = {}

        devices = ADB.list_device()
        if len(devices) != 0:
            devicename = devices[0]
            # SHVJQA0114 SHVJQA00VU SHVJQA016M  SHVJQA00T1 0600240000000001
            # devicename = "SHVJQA00T1"
            os.system("adb -s %s pull /sdcard/Android/data/com.yz.smartpos.yztester/files/Results %s" % (
                devicename, local_path))
        else:
            logger.info("\n\n!!!!!! NO DEVICES!!!!!!!!!!!!")
            devicename = "unkow"
            return
        pass


    def test_tmp(self):
        log_paht = r"D:\log_aip\2470"
        dir_list = os.listdir(log_paht)
        global result_path_g
        for dir in dir_list:
            if dir.startswith("Results_"):
                result_path_g = os.path.join(log_paht, dir)
                if os.path.exists(os.path.join(result_path_g, "case_runned.txt")):
                    logger.info(result_path_g)
                    self.test_result_upload_to_zentao()
        pass

    def test_update_local_caseID(self, local_path, Logger=None):
        case_stepId = os.path.join(local_path, "case_stepId.txt")

        if not os.path.exists(local_path):
            os.makedirs(local_path)

        testcase_stepid_dict = {}

        logger.info("更新caseID列表..........")
        if Logger != None:
            Logger.append("更新caseID列表..........")
        testcase_dict = self.zentao_tool.testcase_browse_all()
        for testcase in testcase_dict.values():
            testcase_stepid_dict[testcase.TCName] = [testcase.id, testcase.stepsId]
        with open(case_stepId, "w") as f:
            for casename_tmp, value_tmp in testcase_stepid_dict.items():
                f.write(casename_tmp + "," + value_tmp[0] + "," + value_tmp[1] + "\n")

    def test_update_local_runID(self, local_path, testtask_id, Logger=None):
        log_path = os.path.join(local_path, testtask_id)

        case_runId = os.path.join(log_path, "case_runId.txt")

        log_path = os.path.join(local_path, testtask_id)
        if not os.path.exists(log_path):
            os.makedirs(log_path)

        testcase_runId_dict = {}

        logger.info("更新("+testtask_id+")runID列表..........")
        logger.info("case_runId:" + case_runId)
        if Logger != None:
            Logger.append("更新("+testtask_id+")runID列表..........")
        caseRunIdDict_tmp = self.zentao_tool.testtask_cases(testtask_id)
        for key, value in caseRunIdDict_tmp.items():
            testcase_runId_dict[key] = value
        with open(case_runId, "w") as f:
            for casename_tmp, value_tmp in testcase_runId_dict.items():
                f.write(casename_tmp + "," + value_tmp + "\n")

    def test_result_upload_to_zentao(self, local_path, testtask_id, Logger=None):
        # 上传测试结果到禅道
        # 需提供2个参数：  1.local_path(本地路径，存放临时日志)；2.testtask_id(禅道上的测试单ID)
        result_path_g = os.path.join(local_path, testtask_id, "Results")
        log_path = os.path.join(local_path, testtask_id)
        if not os.path.exists(log_path):
            os.makedirs(log_path)
        case_upload_ok = os.path.join(log_path, "case_upload_ok.txt")
        case_stepId = os.path.join(local_path, "case_stepId.txt")
        case_runId = os.path.join(log_path, "case_runId.txt")

        case_runned_dict = {}
        case_upload_ok_list = {}

        result_path = result_path_g
        # result_path = os.path.join(log_path, "Results")
        case_runned = os.path.join(result_path, "case_runned.txt")
        testLog_file = os.path.join(result_path, "test.log")
        try:
            if os.path.exists(result_path):
                logger.info(os.listdir(result_path))
                if os.path.getsize(case_runned) > 0:
                    with open(case_runned, "r", encoding='utf-8') as f:
                        for line in f.readlines():
                            case_runned_dict[line.strip().split(",")[3]] = line

                # 解析test.log 获取 casename:testlog 字典
                testlog_content = ""
                with open(testLog_file, "r", encoding='utf-8') as f:
                    testlog_content = f.read()

                # 读取PC本地保存的case_upload
                if os.path.exists(case_upload_ok) == False:
                    with open(case_upload_ok, "w+") as f:
                        pass
                else:
                    with open(case_upload_ok, "r") as f:
                        for line in f.readlines():
                            case_upload_ok_list[line.strip().split(",")[3]] = line

                testcase_runId_dict = {}
                if os.path.exists(case_runId) == False:
                    logger.info("Please update runID list!!! " + case_runId)
                    if Logger != None :
                        Logger.append("Please update runID list!!! " + case_runId);
                    return
                else:
                    with open(case_runId, "r") as f:
                        for line in f.readlines():
                            testcase_runId_dict[line.strip().split(",")[0]] = line.strip().split(",")[1]

                testcase_stepid_dict = {}
                if os.path.exists(case_stepId) == False:
                    logger.info("Please update caseID list!!! " + case_stepId)
                    if Logger != None:
                        Logger.append("Please update caseID list!!! " + case_stepId);
                    return
                else:
                    with open(case_stepId, "r") as f:
                        for line in f.readlines():
                            testcase_stepid_dict[line.strip().split(",")[0]] = [line.strip().split(",")[1], line.strip().split(",")[2]]


                for casename, case_runned in case_runned_dict.items():
                    if casename in case_upload_ok_list and case_upload_ok_list[casename] == case_runned:
                        # logger.info("ignore " + casename)  #上传过的执行结果直接跳过
                        pass
                    else:
                        # 上传结果
                        logger.info("start upload " + casename)
                        test_tmp = case_runned.strip().split(",")
                        test_result = "fail"
                        if test_tmp[4] == "o ":
                            test_result = "pass"
                        elif test_tmp[4] == "x ":
                            test_result = "fail"
                        # test_time = test_tmp[5]

                        # logger.info(test_time)
                        # parttern_str = r"//CaseName:%s\nStartTime:%s(.*?)//END:(.*?)\n" % (casename, test_time)
                        parttern_str2 = r"(//CaseName:%s.*?//END:.*?)\n\n" % (casename)
                        Mode_parttern = re.compile(parttern_str2, flags=re.M | re.DOTALL)
                        testlog_case = re.findall(Mode_parttern, testlog_content)

                        if casename in testcase_runId_dict and casename in testcase_stepid_dict:
                            result = False
                            if len(testlog_case) > 0:
                                # logger.info(testlog_case[-1])
                                result = self.zentao_tool.testtask_runCase(testcase_runId_dict[casename], testcase_stepid_dict[casename][1], test_result, testlog_case[-1])
                            else:
                                result = self.zentao_tool.testtask_runCase(testcase_runId_dict[casename], testcase_stepid_dict[casename][1], test_result)

                            logger.info("upload " + casename + " to " + testtask_id + " " + str(result))
                            if Logger != None:
                                Logger.append("upload " + casename + " to " +testtask_id + " " + str(result))
                            if result:
                                case_upload_ok_list[casename] = case_runned
                        else:
                            if not casename.startswith("test"):
                                logger.info("禅道("+testtask_id +")上没有找到用例 " + casename + "， 请检查！！！！")
                                if Logger != None:
                                    Logger.append("禅道("+testtask_id +")上没有找到用例 " + casename + "， 请检查！！！！")
                        pass

                with open(case_upload_ok, "w") as f:
                    for line in case_upload_ok_list.values():
                        f.write(line)

                if not os.path.basename(result_path).startswith("Results_"):
                    os.renames(result_path,
                               os.path.join(log_path, "Results_" + getCurrentTimeUnderline()))
            else:
                logger.info("Dir not Found:" + result_path)
                if Logger != None:
                    Logger.append("Dir not Found:" + result_path)
        except FileExistsError as e:
            logger.info(e)
            a, b, c = sys.exc_info()
            logger.info(a)
            logger.info(b)
            logger.info(c)
            logger.info('-----------')
            for i in traceback.extract_tb(c):
                logger.info(i)

    def test_result_upload_to_zentao_rtos(self, local_path, testtask_id, Logger=None):
        # 上传测试结果到禅道
        # 需提供2个参数：  1.local_path(本地路径，存放临时日志)；2.testtask_id(禅道上的测试单ID)
        result_path_g = os.path.join(local_path, testtask_id, "Results")
        log_path = os.path.join(local_path, testtask_id)
        if not os.path.exists(log_path):
            os.makedirs(log_path)
        case_upload_ok = os.path.join(log_path, "case_upload_ok.txt")
        case_stepId = os.path.join(local_path, "case_stepId.txt")
        case_runId = os.path.join(log_path, "case_runId.txt")

        case_runned_dict = {}
        case_upload_ok_list = {}

        result_path = result_path_g
        case_runned = os.path.join(result_path, "case_runned.txt")
        testLog_file = os.path.join(result_path, "test.log")
        try:
            if os.path.exists(result_path):
                logger.info(os.listdir(result_path))
                # 解析test.log 获取 casename:testlog 字典
                testlog_content = ""
                with open(testLog_file, "r", encoding='utf-8') as f:
                    testlog_content = f.read()
                    runCase_parttern = re.compile(r"(//CaseName:(.*?)\nStartTime:(.*?)\n.*?//END:(.*?)\n)", flags=re.S)
                    testlog_case_list = re.findall(runCase_parttern, testlog_content)
                    for s in testlog_case_list:
                        tmp_case = None
                        if s[0].count("//CaseName") > 1:
                            index = s[0].rfind("//CaseName")
                            tmp_str = s[0][index:-1]
                            tmp_list = re.findall(r'CaseName:(.*?)\nStartTime:(.*?)\n.*?//END:(.*)', tmp_str, flags=re.S)
                            tmp_case = list(list(tmp_list)[0])
                            tmp_case.insert(0, tmp_str)
                        else:
                            tmp_case = list(s)
                        tmpcase2 = [tmp_case[1].strip(), tmp_case[3].strip(), tmp_case[2].strip(), tmp_case[0].strip()]
                        case_runned_dict[tmpcase2[0].strip()] = tmpcase2

                # 读取PC本地保存的case_upload
                if os.path.exists(case_upload_ok) == False:
                    with open(case_upload_ok, "w+") as f:
                        pass
                else:
                    with open(case_upload_ok, "r") as f:
                        for line in f.readlines():
                            case_upload_ok_list[line.strip().split(",")[3]] = line
                        print("case_upload_ok_list:" + str(case_upload_ok_list))

                testcase_runId_dict = {}
                if os.path.exists(case_runId) == False:
                    logger.info("Please update runID list!!! " + case_runId)
                    if Logger != None:
                        Logger.append("Please update runID list!!! " + case_runId);
                    return
                else:
                    with open(case_runId, "r") as f:
                        for line in f.readlines():
                            testcase_runId_dict[line.strip().split(",")[0]] = line.strip().split(",")[1]

                testcase_stepid_dict = {}
                if os.path.exists(case_stepId) == False:
                    logger.info("Please update caseID list!!! " + case_stepId)
                    if Logger != None:
                        Logger.append("Please update caseID list!!! " + case_stepId);
                    return
                else:
                    with open(case_stepId, "r") as f:
                        for line in f.readlines():
                            testcase_stepid_dict[line.strip().split(",")[0]] = [line.strip().split(",")[1],
                                                                                line.strip().split(",")[2]]

                for casename, case_runned in case_runned_dict.items():
                    if casename in case_upload_ok_list and case_upload_ok_list[casename].split(",")[-1] == case_runned[-2]:
                        logger.info("ignore " + casename)  #上传过的执行结果直接跳过
                        pass
                    else:
                        # 上传结果
                        logger.info("start upload " + casename)
                        test_result = "fail"
                        if case_runned[1] == "PASS":
                            test_result = "pass"
                        else:
                            test_result = "fail"

                        if casename in testcase_runId_dict and casename in testcase_stepid_dict:
                            result = False
                            if len(case_runned[-1]) > 0:
                                result = self.zentao_tool.testtask_runCase(testcase_runId_dict[casename],
                                                                           testcase_stepid_dict[casename][1],
                                                                           test_result, case_runned[-1])
                            else:
                                result = self.zentao_tool.testtask_runCase(testcase_runId_dict[casename],
                                                                           testcase_stepid_dict[casename][1],
                                                                           test_result)

                            logger.info("upload " + casename + " to " + testtask_id + " " + str(result))
                            if Logger != None:
                                Logger.append("upload " + casename + " to " + testtask_id + " " + str(result))
                            if result:
                                case_upload_ok_list[casename] = "0,0,0,"+casename+","+case_runned[1]+","+case_runned[2]
                        else:
                            if not casename.startswith("test"):
                                logger.info("禅道(" + testtask_id + ")上没有找到用例 " + casename + "， 请检查！！！！")
                                if Logger != None:
                                    Logger.append(
                                        "禅道(" + testtask_id + ")上没有找到用例 " + casename + "， 请检查！！！！")
                        pass

                with open(case_upload_ok, "w") as f:
                    for line in case_upload_ok_list.values():
                        f.write(line)

                if not os.path.basename(result_path).startswith("Results_"):
                    os.renames(result_path,
                               os.path.join(log_path, "Results_" + getCurrentTimeUnderline()))
            else:
                logger.info("Dir not Found:" + result_path)
                if Logger != None:
                    Logger.append("Dir not Found:" + result_path)
        except FileExistsError as e:
            logger.info(e)
            a, b, c = sys.exc_info()
            logger.info(a)
            logger.info(b)
            logger.info(c)
            logger.info('-----------')
            for i in traceback.extract_tb(c):
                logger.info(i)
    pass

if __name__ == '__main__':
    Moudles = ["PosTerminal", "CardReaderDevice", "EMVDevice", "PinPadDevice", "PrinterDevice", "ScannerDevice",
               "TagDevice", "PowerManagerDevice", "IntergratedTest", "NetTest2", "Setting"]
    local_path = "D:\\log_aip"
    testtask_id = '3640'
    # testtask_id = '2470'

    apiTools = api_tools(zentaoTools("zhoutian", "zt123456"))

    # # adb 获取日志
    # api_tools.test_result_adb_pull()
    #
    # # 生产caselist
    # Module = "CardReaderDevice"
    # Moudles = ["PosTerminal", "CardReaderDevice", "EMVDevice", "PinPadDevice", "PrinterDevice", "ScannerDevice",
    #            "TagDevice", "PowerManagerDevice", "IntergratedTest", "NetTest2", "Setting"]
    # path = r"G:\git\YZSmartPosApiTest\yztester\src\main\java\com\yz\smartpos\yztester\apifuntest\tests\\"
    # api_tools.test_java_fun(path, Module, Moudles)

    # 上传指定模块的测试用例
    # Module = "PowerManagerDevice"  # "NetTest"
    # apiTools.upload_testcase_toZentao(Module, isLib=False)

    # 上传所有模块的测试用例
    # for Module in Moudles:
    #     apiTools.upload_testcase_toZentao(Module, isCaseLib=False)
    #
    # # 上传测试结果
    # apiTools.test_result_pull_upload_to_zentao(local_path, testtask_id)
    #
    # 获取日志并上传测试结果
    apiTools.test_result_upload_to_zentao_rtos(local_path, testtask_id)

